/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.cli;

import cz.mzk.kramerius.commons.Dom4jUtils;
import cz.mzk.oai.metadataRepository.repository.Repository;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.sysnoSignatureMapping.Mapping;
import cz.mzk.oai.metadataRepository.sysnoSignatureMapping.MappingDocumentBuilder;
import cz.mzk.oai.metadataRepository.sysnoSignatureMapping.MappingsLoader;
import cz.mzk.oai.metadataRepository.sysnoSignatureMapping.RepositoryMappingsLoader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class SaveMappingAction extends Action {

    private File mappingFile;
    private final List<String> collectionNames;

    public SaveMappingAction(Repository repository, List<String> parameters) {
        super(repository);
        this.mappingFile = new File(parameters.get(0));
        this.collectionNames = parameters.subList(1, parameters.size());
    }

    @Override
    public void run() throws Exception {
        List<MetadataCollection> collections = parseCollections();
        MappingsLoader loader = new RepositoryMappingsLoader(collections);
        List<Mapping> mappings = loader.loadMappings();
        saveMappings(mappings);
    }

    private List<MetadataCollection> parseCollections() throws Exception {
        List<MetadataCollection> result = new ArrayList<MetadataCollection>(collectionNames.size());
        for (String collectionName : collectionNames) {
            result.add(findCollection(collectionName));
        }
        return result;
    }

    private MetadataCollection findCollection(String collectionName) throws Exception {
        MetadataCollection result = repository.findCollection(collectionName);
        if (result == null) {
            throw new Exception("There's no such collection '" + collectionName + "'");
        }
        return result;
    }

    private void saveMappings(List<Mapping> mappings) {
        MappingDocumentBuilder builder = new MappingDocumentBuilder(mappings);
        Document doc = builder.getDocument();
        Dom4jUtils.saveDocument(doc, mappingFile);
    }
}
